package com.songshuang.myutilsboot.service.impl;

import com.songshuang.myutilsboot.service.IPdfService;
import com.songshuang.myutilsboot.vo.Result;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class PdfServiceImpl implements IPdfService {

    @Value("${app.storage.base-path:}") // 从配置读取，默认空表示自动选择
    private String configuredBasePath;

    // 获取可靠的存储基路径
    private Path getStorageBasePath() {
        // 优先级1：使用配置路径
        if (!configuredBasePath.isEmpty()) {
            return Paths.get(configuredBasePath);
        }

        // 优先级2：尝试获取JAR所在目录（仅打包运行时有效）
        try {
            Path jarPath = Paths.get(getClass().getProtectionDomain()
                    .getCodeSource().getLocation().toURI());
            if (jarPath.toString().endsWith(".jar")) {
                return jarPath.getParent();
            }
        } catch (Exception ignored) {}

        // 优先级3：使用当前工作目录
        return Paths.get(System.getProperty("user.dir"));
    }

    @Override
    public Result<List<String>> pdfToPng(MultipartFile pdfFile) {
        List<String> imageUrls = new ArrayList<>();
        try {
            // 1. 基础路径准备
            Path basePath = getStorageBasePath();
            Path imagesDir = basePath.resolve("images");

            if (!Files.exists(imagesDir)) {
                Files.createDirectories(imagesDir);
            }

            // 2. 创建时间戳子目录
            String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            Path outputDir = imagesDir.resolve("tmp_" + timestamp);
            Files.createDirectories(outputDir);

            // 3. 处理文件转换
            try (PDDocument document = PDDocument.load(pdfFile.getInputStream())) {
                PDFRenderer renderer = new PDFRenderer(document);
                for (int page = 0; page < document.getNumberOfPages(); page++) {
                    BufferedImage image = renderer.renderImageWithDPI(page, 300);
                    String fileName = "page_" + (page + 1) + ".png";
                    Path outputPath = outputDir.resolve(fileName);
                    ImageIO.write(image, "PNG", outputPath.toFile());
                    imageUrls.add(outputPath.toString());
                }
            }

            return Result.ok(imageUrls);
        } catch (Exception e) {
            return Result.error("路径处理失败: " + e.getMessage());
        }
    }

    @Override
    public ResponseEntity<Resource> downLoadImage(String imagePath) {
        try {
            // 创建文件路径
            Path file = Paths.get(imagePath);

            // 检查文件是否存在
            if (!Files.exists(file)) {
                return ResponseEntity.notFound().build();
            }

            // 创建 UrlResource
            Resource resource = new UrlResource(file.toUri());

            // 检查资源是否可读
            if (resource.exists() || resource.isReadable()) {
                // 设置响应头
                HttpHeaders headers = new HttpHeaders();
                headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"");

                // 返回 ResponseEntity
                return ResponseEntity.ok()
                        .headers(headers)
                        .contentLength(file.toFile().length())
                        .contentType(MediaType.IMAGE_PNG)
                        .body(resource);
            } else {
                return ResponseEntity.badRequest().build();
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
}